import { fetchHome } from '../../services/home/home';
import {getMenuBarRect} from '../../utils/resolution.js';
// 引入 geo 工具函数
import { getDistance, formatDistance } from '../../utils/geo';

let menuBarRect = getMenuBarRect();

Page({
  data: {
    imgSrcs: [],
    tabList: [],
    storeList: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: { type: 'dots' },
    swiperImageProps: { mode: 'scaleToFill' },
    addressComponent: {
      province: '上海市',
      city: '上海市',
      district: '闵行区',
      street: '竹园路',
      formattedAddress: ''
    },
    menuBarRect: menuBarRect
  },

  goodListPagination: {
    index: 0,
    num: 20,
  },

  privateData: {
    tabIndex: 0,
  },

  onShow() {
    this.getTabBar().init();
  },

  onLoad() {
    // 获取地理位置，包含省市区
    this.getLocation();
    this.init();
  },

  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.loadHomePage();
  },

  // 获取地理位置，包含省市区
  getLocation() {
    const self = this;
    const doGet = () => {
      wx.getFuzzyLocation({
        type: 'gcj02',
        success: (loc) => {
          const { latitude, longitude } = loc;
          let storeList = this.data.storeList || [];
          // 计算距离并格式化
          storeList.forEach(store => {
            // lati和long = store.coordinate.split(',')
            const [lon, lat] = store.coordinate.split(',');
            const distance = getDistance(latitude, longitude, lat, lon);
            store.distance = formatDistance(distance);
          });

          console.log('storeList', storeList);

          self.setData({ 
            location: { latitude, longitude },
            storeList
          });
          // 逆地理编码请求（示例）
          const KEY = 'XSBBZ-7E5WT-GJ4XO-LMP7Z-KDFKH-YJBST';
          const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${KEY}`;
          wx.request({
            url,
            success(resp) {
              const comp = resp.data && resp.data.result && resp.data.result.address_component;
              if (comp) {
                self.setData({
                  addressComponent: {
                    province: comp.province,
                    city: comp.city,
                    district: comp.district,
                    street: comp.street || '',
                    formattedAddress: resp.data.result.address || ''
                  }
                });
              }
            },
            fail(err) {
              console.error('reverse geocode fail', err);
            }
          });
        },
        fail(err) {
          console.error('getLocation fail', err);
        }
      });
    };

    wx.getSetting({
      success(res) {
        const has = res.authSetting && res.authSetting['scope.userLocation'];
        if (has) {
          // 已授权，直接获取位置
          doGet();
        } else {
          // 尝试请求授权（首次会弹系统框）
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              doGet();
            },
            fail() {
              // 用户拒绝过，提示并引导去设置页打开
              wx.showModal({
                title: '需要定位权限',
                content: '请在设置中打开定位权限以获取当前位置',
                confirmText: '去设置',
                success(modalRes) {
                  if (modalRes.confirm) {
                    wx.openSetting();
                  }
                }
              });
            }
          });
        }
      },
      fail(err) {
        console.error('getSetting fail', err);
      }
    });
  },

  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });
    fetchHome().then(({ swiper, storeList }) => {
      this.setData({
        storeList: storeList,
        imgSrcs: swiper,
        pageLoading: false,
      });
    });
  },

  tabChangeHandle(e) {
  },

  onReTry() {

  },

  navToSearchPage() {
    wx.navigateTo({ url: '/pages/goods/search/index' });
  },

  navToActivityDetail({ detail }) {
    const { index: promotionID = 0 } = detail || {};
    wx.navigateTo({
      url: `/pages/promotion/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },

  navToStore(e) {
    let id = e.target.id;
    wx.navigateTo({
      url: `/pages/store/store?id=${id}`,
    })
  },

  navToMall() {
    wx.navigateTo({
      url: '/pages/category/index',
    });
  }
});
